<?php

namespace Utuo;

use Think\Template\TagLib;

class T extends TagLib {
	// 标签列表
	protected $tags = array(
			// 一键拨号
			'dial' => array(
					'attr' => 'name',
					'close' => 0 
			),
			// 文章列表
			'article' => array(
					'attr' => 'name,cat,limit,order',
					'close' => 0 
			) 
	);
	
	// 一键拨号
	public function _dial($tag, $content) {
		$tagCode = <<<'PARSE'
			{__name__} = M('ModuleDial')->find($sid);
PARSE;
		return $this->outTag($tag, $tagCode);
	}
	
	// 文章列表
	public function _article($tag, $content) {
		$catId = empty($tag['cat']) ? 0 : intval($tag['cat']);
		$order = empty($tag['order']) ? '' : $tag['order'];
		$limit = empty($tag['limit']) ? '' : intval($tag['limit']);
		$tagCode = <<<'CODE'
			$map['status'] = 1;
			$map['is_deleted'] = 0;
			$map['cid'] = $sid;
			if({catId} == 0){
				empty($cat_id) or $map['cat_id'] = $cat_id;
			} elseif({catId} > 0){
				$map['cat_id'] = {catId};
			}
			{__name__} = M('Article')->where($map)->order({order})->limit({limit})->select();
			foreach({__name__} as &$v){
				$v['url'] = get_url($sid, 'Article', 'show', 'id=' . $v['id']);
			}
CODE;
		$tagValues = array(
				'{catId}' => $catId,
				'{order}' => $order,
				'{limit}' => $limit 
		);
		return $this->outTag($tag, $tagCode, $tagValues);
	}
	
	/**
	 * 解析并输出标签
	 */
	private function outTag($tag, $tagCode, $tagValues = array()) {
		$_trace = empty($tag['_trace']) ? 0 : 1;
		$tagCode = <<<TAG
			<?php
			$tagCode
			$_trace && dump({__name__});
			?>
TAG;
		$tagCode = str_replace('{__name__}', '$' . $tag['name'], $tagCode);
		$tagCode = str_replace(array_keys($tagValues), array_values($tagValues), $tagCode);
		return $tagCode;
	}
}